/**
 *
 */
package com.iknight.mgr.core.utils;

import com.iknight.mgr.core.constant.IkgConstantCode;
import com.iknight.mgr.core.entity.IkgResponse;
import com.iknight.mgr.core.entity.IkgResponseMeta;
import com.iknight.mgr.core.websocket.WebSocketListener;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jeryzym
 */
public final class IkgWebUtils {
    /*
     * @param request
     *
     * @return
     */
    public static boolean isLogin() {
        Subject subject = SecurityUtils.getSubject();
        return subject.getPrincipal() != null;
    }

    /**
     * @param request
     * @return
     */
    public static boolean isLogin(ServletRequest request) {
        return false;
    }

    /**
     * @param request
     * @return
     * @description ajax请求判断
     */
    public static boolean isAjax(HttpServletRequest request) {
        return request.getHeader("x-requested-with") != null
                && request.getHeader("x-requested-with").equals("XMLHttpRequest");
    }

    public static boolean isAjax(ServletRequest request) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        return httpRequest.getHeader("x-requested-with") != null
                && httpRequest.getHeader("x-requested-with").equals("XMLHttpRequest");
    }

    public static JSONObject postIkgResponse(boolean success, String message, Object object) {
        IkgResponse response = new IkgResponse();
        response.setMeta(new IkgResponseMeta(success, message));
        response.setResponseObject(object);
        return JSONObject.fromObject(response);
    }

    /**
     * 向前台返回传参为空
     * @return
     */
    public static JSONObject postIkgParamNullResponse() {
        IkgResponse response = new IkgResponse();
        response.setMeta(new IkgResponseMeta(false, "传入参数为空"));
        response.setResponseObject(IkgConstantCode.PARAMSNULL);
        return JSONObject.fromObject(response);
    }

    public static JSONObject postIkgSaveSucResponse() {
        IkgResponse response = new IkgResponse();
        response.setMeta(new IkgResponseMeta(true, "保存成功!"));
        response.setResponseObject(IkgConstantCode.OPERSUCCESS);
        return JSONObject.fromObject(response);
    }

    /**
     * 删除成功
     *
     * @return
     */
    public static JSONObject postIkgDelSucResponse() {
        IkgResponse response = new IkgResponse();
        response.setMeta(new IkgResponseMeta(true, "删除成功!"));
        response.setResponseObject(IkgConstantCode.OPERSUCCESS);
        return JSONObject.fromObject(response);
    }

//    public static JSONObject postIkgResponse(boolean success, String message, Object object, Object dicts) {
//        IkgResponse response = new IkgResponse();
//        response.setMeta(new IkgResponseMeta(success, message));
//        response.setResponseObject(object);
//        response.setDicts(dicts);
//
//        return JSONObject.fromObject(response);
//    }

    /**
     * @param msg
     * @param statusCode
     * @return
     * @description 返回数据格式
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    @Deprecated
    public static JSONObject postMsg(String msg, String statusCode, boolean success) {
        Map result = new HashMap<String, Object>();
        result.put("msg", msg);
        result.put("statusCode", statusCode);
        result.put("success", success);
        return JSONObject.fromObject(result);
    }

    @Deprecated
    public static JSONObject postMsg(Object obj, String statusCode, boolean success) {
        Map result = new HashMap<String, Object>();
        result.put("result", obj);
        result.put("statusCode", statusCode);
        result.put("success", success);
        return JSONObject.fromObject(result);
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Deprecated
    public static Map<String, Object> postMsg(String msg, Object statusCode, boolean success) {
        Map result = new HashMap<String, Object>();
        result.put("msg", msg);
        result.put("statusCode", statusCode);
        result.put("success", success);
        return result;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Deprecated
    public static Map<String, Object> postMsg(String msg, Object statusCode, boolean success, String redirectUrl) {
        Map result = new HashMap<String, Object>();
        result.put("msg", msg);
        result.put("statusCode", statusCode);
        result.put("success", success);
        result.put("redirectUrl", redirectUrl);
        return result;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Deprecated
    public static JSONObject postParamNullResult() {
        Map result = new HashMap<String, Object>();
        result.put("msg", "传入参数为空");
        result.put("statusCode", IkgConstantCode.PARAMSNULL);
        result.put("success", false);
        return JSONObject.fromObject(result);
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Deprecated
    public static JSONObject postOperSucResult() {
        Map result = new HashMap<String, Object>();
        result.put("msg", "操作成功");
        result.put("statusCode", IkgConstantCode.OPERSUCCESS);
        result.put("success", true);
        return JSONObject.fromObject(result);
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Deprecated
    public static JSONObject postOperFailResult() {
        Map result = new HashMap<String, Object>();
        result.put("msg", "操作失败");
        result.put("statusCode", IkgConstantCode.OPERFAILURE);
        result.put("success", false);
        return JSONObject.fromObject(result);
    }

    @Deprecated
    public static JSONObject postMsg(Object result) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        if (null == result) {
            map.put("result", "");
        } else {
            map.put("result", result);

        }

        return JSONObject.fromObject(map);
    }

    /**
     * 列表数据固定返回格式
     *
     * @param total
     * @param result
     * @return
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static Map<String, Object> postResult(long total, List result) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("total", total);
        resultMap.put("rows", result);
        return JSONObject.fromObject(resultMap);
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Deprecated
    public static Map<String, Object> postResult(List result) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("rows", result);
        return JSONObject.fromObject(resultMap);
    }

    @Deprecated
    public static Map<String, Object> postResult(boolean success, String msg) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("success", success);
        resultMap.put("msg", msg);
        return resultMap;
    }

    /**
     * @return
     * @description 判断登录或缓存是否失效
     */
    public static boolean sessionExpired() {
        Subject current = SecurityUtils.getSubject();
        Session session = current.getSession();
        Object user = current.getPrincipal();
        return session == null || user == null;
    }

    /**
     * @return
     * @description shiro框架下获取当前登录用户
     */
    public static String getCurrentUser() {
        Subject current = SecurityUtils.getSubject();
        Session session = current.getSession();
        Object user = current.getPrincipal();
        if (session == null || user == null) {
            return null;
        }
        return String.valueOf(user);
    }

    public static Object fireSessionExpiredEvent() {
        return JSONObject.fromObject(IkgWebUtils.postMsg("当前登录已失效,请重新登录", IkgConstantCode.SESSIONEXPIRED, false));
    }

    /**
     * 向前端发送json数据
     *
     * @param response
     * @param responseObject
     */
    public static void sendJson(HttpServletResponse response, Object responseObject) {
        JSONObject responseJSONObject = JSONObject.fromObject(responseObject);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.append(responseJSONObject.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    public static void sendMsg(String code, String msg) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS");
        StringBuffer message = new StringBuffer();
        message.append(sdf.format(Calendar.getInstance().getTime())).append(" -> ").append(msg);
        WebSocketListener.sendMessage(code, message.toString());
    }
}
